package org.jili.novoland.game;

import org.jili.novoland.base.Actor;
import org.jili.novoland.base.Layer;
import org.jili.novoland.base.Sprite;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.Log;

public class Person extends Sprite implements Actor{
    private int direct = BattleMap.DIRECT_EAST;
    final static private int DEFAULT_SPEED = 2;
    final static private int ROLE_WIDTH = 48;
    final static private int ROLE_HEIGHT = 72;
    
    private int stepX, stepY;
    
    
    private int targetX, targetY;
    private boolean isMoving = false;
    private Rect moveImg[][] = new Rect[4][4]; 
    

    public Person(Bitmap img) {
        super(img, ROLE_WIDTH, ROLE_HEIGHT);
        for (int i = 0; i < 4;i++){
            for (int j = 0; j < 4;j++){
                moveImg[i][j] = new Rect(j * width, i * height, width, height);
            }
        }
    }
    
    public void moveTo(int tx,int ty){
        int dx = tx - x;
        int dy = ty - y;

        if(dx == 0 && dy == 0){
            isMoving = false;
            return;
        }else{
            isMoving = true;
        }

        if(dx > Math.abs(dy))
            direct = BattleMap.DIRECT_EAST;
        else if (-dx > Math.abs(dy))
            direct = BattleMap.DIRECT_WEST;
        
        if(dy > Math.abs(dx))
            direct = BattleMap.DIRECT_SOUTH;
        else if ( -dy > Math.abs(dx))
            direct = BattleMap.DIRECT_NORTH;
        int frame[] = {direct, direct + 1 , direct + 2, direct +3};
        
        double s = Math.sin(Math.atan((double)dx/dy));
        double c = Math.cos(Math.atan((double)dx/dy));
        double s1 = Math.sin(Math.atan((double)dx/dy)) * DEFAULT_SPEED; 
        double s2 = Math.cos(Math.atan((double)dx/dy)) * DEFAULT_SPEED;
        stepY = new Double(s1).intValue(); 
        stepX = new Double(s2).intValue();
        setFrameSequence(frame);
    }
    
    private boolean moveToPostion(){
        if(isMoving &&  
                (Math.abs(stepX) < Math.abs(targetX - x) && Math.abs(stepY) < Math.abs(targetY - y))){
            isMoving = true;
        }else{
            isMoving = false;
            stepX = stepY = 0;
            targetX = x;
            targetY = y;
            return true;
        }
        return !isMoving;
    }

    public void tick() {
        if(!moveToPostion()){
            move(stepX,stepY);
            nextFrame();
        }
        
    }

}
